import React, { Component } from 'react';
import { Table, Row, Col, Button, Form, Input, Tabs, Icon, Divider, Modal, notification, Select, DatePicker, Drawer, InputNumber, Cascader, Checkbox } from 'antd';
import * as APIService from '../../axios/api';
import moment from 'moment';
import * as utils from '../../utils/action';
const FormItem = Form.Item;
const { TabPane } = Tabs;
const { confirm } = Modal;
const { Option } = Select;
//弹出通知提醒框
function openNotification(type, message) {
	notification.open({
		type: type,
		message: message,
		duration: 2,
	});
};

const dateFormat = 'YYYY-MM-DD';
class TableSearch extends Component {
	state = {
		dataSource: [],
		pagination: {
			pageSize: 10,
			current: 1
		},
		loading: false,
		chooseData: '',
		visible_user: false,
		visible_role: false,
		roleData: [],
		options: [],
		roleList: [],
		handleType: 0,
		columns: [
			{
				title: '序号',
				width: 80,
				render: (text, record, index) => {
					return (
						`${(this.state.pagination.current - 1) * (this.state.pagination.pageSize) + (index + 1)}`
					)
				}
			},
			{
				title: '姓名',
				dataIndex: 'userName',
			},
			{
				title: '部门名称',
				dataIndex: 'departmentName',
			},
			{
				title: '账号',
				dataIndex: 'account'
			},
			{
				title: '电话',
				dataIndex: 'phone'
			},
			{
				title: '邮箱',
				dataIndex: 'mailbox'
			},
			{
				title: '操作',
				width: 280,
				render: (text, record) => {
					return <span>
						<a onClick={() => this.showUserDrawer(record, 1)}>修改</a>
						<Divider type="vertical" />

						<a onClick={() => this.showRoleDrawer(record)}>角色分配</a>
						<Divider type="vertical" />
						<a onClick={() => this.showDeleteConfirm(record, 0)}>
							删除
						</a>
						<Divider type="vertical" />
						<a onClick={() => this.showDeleteConfirm(record, 1)}>
							重置密码
						</a>
					</span>
				}
			}
		],
		deptDataSource: [],
	};

	componentWillMount() {
		this.setState({
			condition: '&pageNum=' + this.state.pagination.current + '&pageSize=' + this.state.pagination.pageSize
		})
		this.fetch('&pageNum=' + this.state.pagination.current + '&pageSize=' + this.state.pagination.pageSize);
	}

	componentWillUnmount() {
		this.setState = () => {
			return;
		};
	}

	showUserDrawer = (data, type) => {
		if (type === 1) {
			var ids = [];
			console.log(data, 'data');
			for (var value of data.departmentList) {
				ids.push(value.id)
			}
			// ids.push(data.departmentId)
			this.props.form.setFieldsValue({
				userName: data.userName,
				account: data.account,
				mailbox: data.mailbox,
				phone: data.phone,
				// birthday: moment(data.birthday, dateFormat),
				departmentId: ids
				// departmentId: data.departmentId
			})

		}
		this.setState({
			visible_user: true,
			handleType: type,
			chooseData: data
		});
	};

	showRoleDrawer = (data) => {

		var list = [];
		for (var value of data.roleList) {
			list.push(value.id);
		}
		console.log(list)
		this.setState({
			roleList: list,
			visible_role: true,
			chooseData: data,

		});
	}

	handleCancel = () => {
		this.props.form.resetFields();
		this.setState({
			visible_user: false,
			visible_role: false,
		});
	};
	//弹出删除框
	showDeleteConfirm = (data, type) => {
		const that = this;
		confirm({
			title: type === 0 ? '确认删除' + '[' + data.userName + ']？' : '确认重置密码？',
			okText: '确认',
			okType: 'warning',
			cancelText: '取消',
			onOk() {
				if (type === 0) {
					APIService.deleteUser(data.userId).then(data => {
						openNotification('success', '删除成功');

					}).catch(function (error) {
						openNotification('error', error.message);
					});
				} else {
					APIService.resetPassword(data.userId).then(data => {
						openNotification('success', '重置成功');
					}).catch(function (error) {
						openNotification('error', error.message);
					});
				}
				that.fetch(that.state.condition);

			},
			onCancel() {
				console.log('Cancel');
			},
		});
	}
	// 切换分页
	handleTableChange = (pagination, filters, sorter) => {
		this.props.form.validateFields((err, values) => {

			const pager = { ...this.state.pagination };
			pager.current = pagination.current;
			pager.pageSize = pagination.pageSize;
			var str = '';
			if (values.userName_search !== undefined && values.userName_search !== '') {
				str += '&userName=' + values.userName_search;
			}
			if (values.account_search !== undefined && values.account_search !== '') {
				str += '&account=' + values.account_search;
			}
			str += '&pageNum=' + pagination.current + '&pageSize=' + pagination.pageSize;
			this.fetch(str);
			this.setState({
				pagination: pager,
				condition: str
			});
		});
	};
	fetch = (str) => {
		this.setState({ loading: true });
		APIService.getUsers(str).then(data => {
			const pagination = { ...this.state.pagination };
			pagination.total = data.data.data.total;
			pagination.style = utils.pageStyle;
			pagination.showSizeChanger = true;
			pagination.showQuickJumper = true;
			pagination.showTotal = total => `共 ${total} 条数据`
			this.setState({
				loading: false,
				dataSource: data.data.data.data,
				pagination,
			});

		})
		//查询所有的角色
		APIService.getRoles().then(data => {
			const dataSource = data.data.data.data;
			this.setState({
				roleData: dataSource
			})
		})
		//查询所有部门组装成级联选择框
		APIService.getDepartMents().then(data => {
			// console.log('部门数据', data.data.data);
			const dataSource = data.data.data;
			const options = [], deptDataSource = [];
			for (var value of dataSource) {
				var json = { "label": value.name, "value": value.id, 'children': [] }

				if (value.children.length !== 0) {
					for (var valueFirst of value.children) {
						// var json2 = { "label": valueFirst.name, "value": valueFirst.id, 'children': [] }
						var json2 = { "label": valueFirst.name, "value": valueFirst.id }
						json.children.push(json2)
					}
				}
				options.push(json);

				// deptDataSource
				if (value.children.length > 0) {
					for (var valueFirst of value.children) {
						var obj = { ...valueFirst, parentName: value.name, parentId: value.id }
						deptDataSource.push(obj)
					}
				} else {
					deptDataSource.push(value)
				}
			}
			console.log('部门最终数据', deptDataSource);
			// console.log('部门最终数据', options);
			this.setState({
				options: options,
				deptDataSource,
			})
		}
		)
	}
	onChange = (checkedValues) => {
		console.log('checked = ', checkedValues);
		this.setState({
			roleList: checkedValues
		})
	}
	//添加修改用户提交
	submitUser = (e) => {
		this.props.form.validateFields(['account', 'userName', 'departmentId', 'mailbox', 'phone'], (err, values) => {
			if (!err) {
				console.log(values.departmentId, 'values.departmentId');
				// values.departmentId = values.departmentId.length > 0 ? values.departmentId.join(',') : null
				values.departmentId = values.departmentId === undefined ? 0 : values.departmentId[values.departmentId.length - 1];  // 级联选择
				if (this.state.handleType === 0) {
					values = Object.assign({}, values, { creatorId: parseInt(localStorage.getItem('userId')) })
				} else {
					values = Object.assign({}, values, { updaterId: parseInt(localStorage.getItem('userId')), id: this.state.chooseData.userId })
				}
				const that = this;
				// console.log(values.departmentId);
				APIService.addOrUpdateUser(values).then(data => {
					if (data.data.code === 200) {
						openNotification('success', '操作成功')
					} else {
						openNotification('warning', data.data.msg)
					}
					that.handleCancel();
					that.fetch(that.state.condition);
				})

			} else {
				console.log(err);
			}
		});
	}
	//角色分配
	submitRole = (e) => {
		var values = { creatorId: parseInt(localStorage.getItem('userId')), userId: this.state.chooseData.userId, roleIdList: this.state.roleList }

		APIService.roleAssignment(values).then(data => {
			if (data.data.code === 200) {
				openNotification('success', '操作成功')
			} else {
				openNotification('warning', data.data.msg)
			}
			this.handleCancel();
			this.fetch(this.state.condition);
		})
	}
	onSelectedRowKeysChange = selectedRowKeys => {
		this.setState({ selectedRowKeys });
	};
	handleSearch = (e) => {
		this.props.form.validateFields(['userName_search', 'account_search'], (err, values) => {
			var str = '';
			if (values.userName_search !== undefined) {
				str += '&userName=' + values.userName_search;
			}
			if (values.account_search !== undefined) {
				str += '&account=' + values.account_search;
			}
			this.fetch(str);

		});
	};


	render() {
		const { getFieldDecorator } = this.props.form;

		const formItemLayout = {
			labelCol: {
				xs: {
					span: 30
				},
				sm: {
					span: 6
				},
			},
			wrapperCol: {
				xs: {
					span: 24
				},
				sm: {
					span: 18
				},
			},
		};
		var RoleOptions = (props) => {
			const { roleData } = this.state;
			return roleData.map((wds, idx) => (
				<Col span={12} key={idx}>
					<Checkbox value={wds.roleId}>{wds.roleName}</Checkbox>
				</Col>
			))
		}
		var operations = <div className="mydiv" > <Button icon="plus" onClick={() => this.showUserDrawer([], 0)} type="primary" > 新增 </Button></div >
		return (
			<div className="shadow-radius">
				<Form className="search-form" style={{ paddingBottom: 0 }}>
					<Row gutter={24}>
						<Col span={4}>
							<FormItem label="姓名">
								{getFieldDecorator('userName_search')(
									<Input placeholder='请输入姓名' />
								)}
							</FormItem>
						</Col>
						<Col span={4}>
							<FormItem label="账号">
								{getFieldDecorator('account_search')(
									<Input placeholder='请输入账号' />
								)}
							</FormItem>
						</Col>
						<Col span={2} style={{ marginRight: '10px', display: 'flex' }} className="serarch-btns">
							<FormItem>
								<Button icon="search" type="primary" htmlType="submit" className={'btn'} onClick={this.handleSearch}>
									查询
								</Button>
							</FormItem>

						</Col>
					</Row>
				</Form>
				<Tabs tabBarExtraContent={operations} >
					<TabPane tab={<span><Icon type="table" /><strong>用户管理</strong> </span>} key="1">
						<Table columns={this.state.columns} dataSource={this.state.dataSource} loading={this.state.loading} onChange={this.handleTableChange} pagination={this.state.pagination} rowKey={record => record.userId} />
					</TabPane>

				</Tabs>
				{/* 按钮drawer */}
				<Drawer title="新增/修改用户" placement="right" closable={true} onClose={this.handleCancel} visible={this.state.visible_user} width='600px' >
					<Form {...formItemLayout}>
						<Row gutter={16} >
							<Col span={12}> <Form.Item label={< span > 账号 </span>}> {getFieldDecorator('account', { rules: [{ required: true, message: '请输入账号', whitespace: true }], })
								(< Input placeholder="账号" />)}
							</Form.Item >
							</Col>
							<Col span={12} ><Form.Item label={<span> 姓名 </span >}> {
								getFieldDecorator('userName', { rules: [{ required: true, message: '请输入姓名', whitespace: true }], })
									(< Input placeholder="请输入姓名" />)}
							</Form.Item>
							</Col>
							<Col span={12} ><Form.Item label={<span> 电话 </span >}> {
								getFieldDecorator('phone', { rules: [{ required: true, message: '请输入正确的电话', pattern: new RegExp(/^1[3456789]\d{9}$/, "g"), }] })
									(< Input placeholder="请输入电话" />)}
							</Form.Item>
							</Col>
							<Col span={12} >
								<Form.Item label="部门">
									{/* 级联选择 */}
									{getFieldDecorator('departmentId')(<Cascader options={this.state.options} />)}   
									{/* select 多选 */}
									{/* {getFieldDecorator('departmentId')(
										<Select placeholder='请选择部门' mode='multiple' allowClear>
											{
												this.state.deptDataSource && this.state.deptDataSource.map(item => {
													return <Option key={item.id} value={item.id}>{item.parentName ? item.parentName + ' - ' + item.name : item.name}</Option>
													// return <Option key={item.id} value={item.id}>{item.parentName + ' - ' + item.name}</Option>
												})
											}
										</Select>
									)} */}
								</Form.Item>
							</Col>
							<Col span={12} ><Form.Item label={<span> 邮箱 </span >}> {
								getFieldDecorator('mailbox')
									(< Input placeholder="请输入邮箱" />)}
							</Form.Item>
							</Col>

						</Row>
					</Form >
					<div
						style={{
							position: 'absolute',
							right: 0,
							bottom: 0,
							width: '100%',
							borderTop: '1px solid #e9e9e9',
							padding: '10px 16px',
							background: '#fff',
							textAlign: 'right',
						}}
					>
						<Button onClick={this.handleCancel} style={{ marginRight: 8 }}>
							取消
						</Button>
						<Button type='primary' onClick={this.submitUser} style={{ marginRight: 8 }}>
							保存
						</Button>
					</div>
				</Drawer >
				<Drawer title="新增/修改用户" placement="right" closable={true} onClose={this.handleCancel} visible={this.state.visible_role} width='600px' >
					<Form>
						<Checkbox.Group style={{ width: '100%' }} value={this.state.roleList} onChange={this.onChange}>
							<Row gutter={16}>
								<RoleOptions />
							</Row>
						</Checkbox.Group>
					</Form>

					<div
						style={{
							position: 'absolute',
							right: 0,
							bottom: 0,
							width: '100%',
							borderTop: '1px solid #e9e9e9',
							padding: '10px 16px',
							background: '#fff',
							textAlign: 'right',
						}}
					>
						<Button onClick={this.handleCancel} style={{ marginRight: 8 }}>
							取消
						</Button>
						<Button type='primary' onClick={this.submitRole} style={{ marginRight: 8 }}>
							保存
						</Button>
					</div>
				</Drawer>
			</div>
		);
	}
}

export default Form.create()(TableSearch);
